var crc = require('crc');
var fecha = require('fecha');
var ACNT = require("../mock/hk/ACNT");
var HFK = require("../mock/hk/HFK");
var HSK = require("../mock/hk/HSK");
var HFP = require("../mock/hk/HFP");
var Loop = require("../mock/hk/Loop");
var PM = require("../mock/hk/PM");
var PROJ = require("../mock/hk/PROJ");
var ROUT = require("../mock/hk/ROUT");
var SIGNAL = require("../mock/hk/SIGNAL");
var SWCH = require("../mock/hk/SWCH");
var _ = require('underscore');

var trackManageArr = [new ACNT(),new HFK(),new HFP(),new HSK(),new Loop(),new PM(),new PROJ(),new ROUT(),new SIGNAL(),new SWCH()];

/*依照汉卡协议模拟发出数据结构*/
var STX = 0x02;
var ETX = 0x03;
exports.createBuffer = function(data){
    console.log('-------------xxx');
    var startBuffer = new Buffer(1);
    startBuffer.writeUInt8(STX,0);
    var headBuffer = new Buffer(26);
    headBuffer.write(data.serviceId,0);
    var timeDateStr = fecha.format(new Date(),'YYYY.MM.DD_hh:mm:ss')
    headBuffer.write(timeDateStr,1);
    headBuffer.writeInt32BE(data.seqCounter,20);
    headBuffer.writeUInt8(data.protocolVersion,24);
    headBuffer.writeUInt8(0x3C,25);
    var payloadBuffer = new Buffer(data.payloadData);
    var buffer = new Buffer(1);
    buffer.writeUInt8(0x3E,0);
    var checkBuffer = Buffer.concat([headBuffer,payloadBuffer,buffer],(27+payloadBuffer.length));
    var tailBuffer = new Buffer(4);

    tailBuffer.writeInt32BE(crc.crc16(checkBuffer),0);
    var endBuffer = new Buffer(1);
    endBuffer.writeUInt8(ETX,0);
    return  Buffer.concat([startBuffer,headBuffer,payloadBuffer,buffer,tailBuffer,endBuffer],(33+payloadBuffer.length));
}
/*解析从终端返回的buffer数据结构*/
exports.resolveStr = function(str){
    var infos = [];
    var content = str.substring(2,str.length-2);
    var timeStamp = content.substring(0,24);
    var protocolContent = content.substring(content.indexOf("<") + 2 , content.lastIndexOf(">") - 1);
    var startIndex = 0;
    var infoType = protocolContent.substring(startIndex , startIndex + 4);
    console.log(protocolContent);
    //console.log(infoType);
    var loopFlag = false;
    while(startIndex<=protocolContent.length){
        _.forEach(trackManageArr,function(obj,index){
           if(obj.TYPE === infoType){
             //console.log(obj);
             startIndex = obj.resolve(protocolContent,startIndex);
             //  console.log(obj);
             //  console.log(startIndex);
             infos.push(obj);
             loopFlag = true;
           }
        });
        if(!loopFlag){
            startIndex += 4;
            loopFlag = false;
            continue;
        }
            startIndex += 1;
            infoType = protocolContent.substring(startIndex , startIndex + 4);
            loopFlag = false;
            console.log(infoType)
   }
    console.log(infos);
    return infos;
}